"""
债券数据API路由
"""

from fastapi import APIRouter, Depends, Query
from typing import List, Optional
from datetime import date
from sqlalchemy.orm import Session
from sqlalchemy import and_

from src.models.base import get_db
from src.models.financial import BondInfo, BondDailyQuote
from src.schemas.bonds import BondDailySchema

router = APIRouter(prefix="/bonds", tags=["债券数据"])

@router.get("/", response_model=List[dict])
def get_bonds(
    bond_type: Optional[str] = Query(None, description="债券类型: 国债/企业债/可转债"),
    issuer: Optional[str] = Query(None, description="发行主体"),
    db: Session = Depends(get_db)
):
    """获取债券基本信息列表"""
    query = db.query(BondInfo)
    
    if bond_type:
        query = query.filter(BondInfo.type == bond_type)
    if issuer:
        query = query.filter(BondInfo.issuer.like(f"%{issuer}%"))
        
    return [{
        "code": bond.code,
        "name": bond.name,
        "type": bond.type,
        "issue_date": bond.issue_date,
        "maturity_date": bond.maturity_date,
        "coupon_rate": float(bond.coupon_rate),
        "issuer": bond.issuer
    } for bond in query.order_by(BondInfo.code).all()]

@router.get("/{bond_code}/daily", response_model=List[BondDailySchema])
def get_bond_daily(
    bond_code: str,
    start_date: Optional[date] = Query(None),
    end_date: Optional[date] = Query(None),
    db: Session = Depends(get_db)
):
    """获取债券日行情数据"""
    bond = db.query(BondInfo).filter(BondInfo.code == bond_code).first()
    if not bond:
        return []
    
    query = db.query(BondDailyQuote).filter(BondDailyQuote.bond_id == bond.id)
    
    if start_date:
        query = query.filter(BondDailyQuote.trade_date >= start_date)
    if end_date:
        query = query.filter(BondDailyQuote.trade_date <= end_date)
        
    return query.order_by(BondDailyQuote.trade_date).all()

@router.get("/yield-curve")
def get_yield_curve(
    curve_type: str = Query("treasury", description="收益率曲线类型: treasury/corporate"),
    db: Session = Depends(get_db)
):
    """获取债券收益率曲线数据"""
    # 实现收益率曲线查询逻辑
    pass